package com.bootdo.front.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.bootdo.common.domain.KLineDO;
import com.bootdo.common.utils.HttpRequestUtil;
import com.bootdo.common.utils.StringUtils;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;

@Controller
public class FrontTestController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private JavaMailSender mailSender;

    public static final String host = "smtp.gmail.com";

    public static final String username = "venusingvip@gmail.com";

    public static String finalpassword = "bsnchgqhjkenudwr";

    public static final String encoding = "UTF-8";

    public static final String port = "465";

    @RequestMapping("/mongdb/send")
    public void sendMail(){
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("venusingvip@gmail.com");
        message.setTo("2267483398@qq.com");
        message.setSubject("it is a test for spring boot");

        message.setText("你好，我是小黄，我正在测试发送邮件。");
        try {
            mailSender.send(message);
            logger.info("小黄的测试邮件已发送。");
        } catch (Exception e) {
            logger.error("小黄发送邮件时发生异常了！", e);
        }
    }



    private static MongoClient mongoClient;

    public static final String ip = "49.0.200.220";   //ip地址

    public static final String symbolList[] = { "BTC/USDT", "ETH/USDT", "XRP/USDT", "BCH/USDT", "BSV/USDT","LTC/USDT", "EOS/USDT","YFII/USDT","YFI/USDT","NEO/USDT","BZB/USDT","DASH/USDT","ETC/USDT"};;   //币种

    //public static final String symbolList[] = { "BTC/USDT", "ETH/USDT", "XRP/USDT", "BCH/USDT", "BSV/USDT","LTC/USDT", "EOS/USDT","NEO/USDT","BZB/USDT","DASH/USDT"};;   //币种
    public static final String from = "1593532800000";  //开始时间  2020-07-01 00:00:00
    //public static final String from = "1629999000000";  //开始时间  2021-08-27 01:30:00
    public static final String to = "1634410800000";  //结束时间  2021-10-17 03:00:00
    public static final String resolution = "1M"; //K线类型（1,5,15,30,60,1D,1W,1M）
    public static final String Period = "1mon"; //（1min,5min,15min,30min,1hour,1day,1week,1mon）

    //public static final String url = "http://49.234.13.106:8801/market/history";
    public static final String url = "http://api.bizzan.pro/market/history";

    public static void main(String[] args) {
        try {

            List<ServerAddress> seeds = new ArrayList<ServerAddress>();
            seeds.add( new ServerAddress( ip ));
            List<MongoCredential> credentials = new ArrayList<MongoCredential>();
            credentials.add(
                    MongoCredential.createScramSha1Credential(
                            "bizzan",
                            "bizzan",
                            "bizzan123456".toCharArray()
                    )
            );
            mongoClient = new MongoClient( seeds, credentials );

            //连接MongoDB服务器，端口号为27017
            //mongoClient = new MongoClient(ip, 27017);
            //连接数据库
            MongoDatabase mDatabase = mongoClient.getDatabase("bizzan");  //test可选
            System.out.println("mongdb链接成功!");
            System.out.println("MongoDatabase 数据库为 : "+mDatabase.getName());
            //获取所有集合
            //MongoIterable<String> colls = getDB("bizzan").listCollectionNames();
            //遍历币种，获取历史数据
            for(String symbol : symbolList) {
                //创建集合(集合不存在，创建集合)
                getDB("bizzan").createCollection("exchange_kline_" + symbol +"_1mon");
                //获取历史列表数据
                List<KLineDO> list = getDataList(symbol);
                //导入数据
                insertManyTest(list,symbol);
            }
        } catch (Exception e) {
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
        }
    }

    // =================公用用方法=================

    /**
     * 插入多个文档数据
     * @param list
     */
    public static void insertManyTest(List<KLineDO> list,String symbol){
        //获取集合
        MongoCollection<Document> collection = getCollection("bizzan","exchange_kline_"+symbol+"_"+list.get(0).getPeriod());
        //要插入的数据
        List<Document> docList = new ArrayList<>();
        Document document = null;
        for(KLineDO kLineDO : list) {
            document = new Document("_id",kLineDO.get_id())
                    .append("_class", kLineDO.get_class())
                    .append("openPrice", kLineDO.getOpenPrice())
                    .append("highestPrice", kLineDO.getHighestPrice())
                    .append("lowestPrice", kLineDO.getLowestPrice())
                    .append("closePrice", kLineDO.getClosePrice())
                    .append("time", kLineDO.getTime())
                    .append("period", kLineDO.getPeriod())
                    .append("count", kLineDO.getCount())
                    .append("volume", kLineDO.getVolume())
                    .append("turnover", kLineDO.getTurnover());
            docList.add(document);
        }
        //插入多个文档
        collection.insertMany(docList);
    }

    /**
     * 获取DB实例 - 指定数据库，若不存在则创建
     * @param dbName
     * @return
     */
    public static MongoDatabase getDB(String dbName) {
        if (dbName != null && !"".equals(dbName)) {
            MongoDatabase database = mongoClient.getDatabase(dbName);
            return database;
        }
        return null;
    }

    /**
     * 获取指定数据库下的collection对象
     * @param collName
     * @return
     */
    public static MongoCollection<Document> getCollection(String dbName, String collName) {
        if (null == collName || "".equals(collName)) {
            return null;
        }
        if (null == dbName || "".equals(dbName)) {
            return null;
        }
        MongoCollection<Document> collection = mongoClient.getDatabase(dbName).getCollection(collName);
        return collection;
    }

    /**
     * 获取K线历史数据
     * @return
     */
    public static List<KLineDO> getDataList(String symbol) {
        List<JSONArray> list = new ArrayList<JSONArray>();
        List<KLineDO> list1 = new ArrayList<KLineDO>();
        String param = "symbol="+ symbol +"&from=" + from + "&to=" + to + "&resolution=" + resolution;
        System.out.println("请求地址：" + url);
        System.out.println("请求参数：" + param);
        String data = HttpRequestUtil.sendGet(url,param);
        if(StringUtils.isNotBlank(data)) {
            list = JSON.parseObject(data, List.class);
            KLineDO kLineDO = null;
            for(JSONArray jsonArray : list) {
                kLineDO = new KLineDO();
                kLineDO.setPeriod(Period);
                kLineDO.setTime((Long) jsonArray.get(0));
                kLineDO.setOpenPrice(jsonArray.get(1).toString());
                kLineDO.setHighestPrice(jsonArray.get(2).toString());
                kLineDO.setLowestPrice(jsonArray.get(3).toString());
                kLineDO.setClosePrice(jsonArray.get(4).toString());
                kLineDO.setTurnover(jsonArray.get(5).toString());
                kLineDO.setVolume(jsonArray.get(5).toString());
                list1.add(kLineDO);
            }
        }
        System.out.println("去重前数据为" + list1.size() + "条");
        //根据时间戳去重
        list1 = list1.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(KLineDO :: getTime))), ArrayList::new));
        System.out.println("去重后数据为" + list1.size() + "条");
        return list1;
    }

}
